from time import sleep

import usb2IIC.usb2iic as i2c
import luinit

dev = luinit.init()
iic_config = i2c.IIC_CONFIG(400000, 1, 7, 1)
ret = i2c.IIC_Init(dev, 0, i2c.byref(iic_config))
print(ret)
# 扫描IIC总线上能正常应答的设备
SlaveAddr = (i2c.c_ushort * 128)()
SlaveAddrNum = i2c.IIC_GetSlaveAddr(dev, 0, i2c.byref(SlaveAddr))

# class WriteBuffer(object):
#     pass


if SlaveAddrNum <= 0:
    print("Get iic address faild!")
    exit()
else:
    print("Get iic address sunccess!")
    print("IIC addr:")
    for i in range(0, SlaveAddrNum):
        print("%02X " % SlaveAddr[i], end='')
    print("")
    # 向0x08地址开始连续写8字节数据
WriteBuffer = (i2c.c_byte * 1)()
# WriteBuffer[0] = p >> 5
# WriteBuffer[1] = 0x90
# for i in range(0, 8):
#     WriteBuffer[2 + i] = p * 8 + i
# ret = i2c.IIC_WriteBytes(dev, 0, 0x48, i2c.byref(WriteBuffer), 10, 100)
# if ret != i2c.IIC_SUCCESS:
#     print("Write iic faild!")
#     exit()
# else:
#     print("Write iic sunccess!")
# 从0x08地址开始读取8字节数据
ReadBuffer = (i2c.c_byte * 1)()
# WriteBuffer = 0x01
WriteBuffer[0] = 0x01
# WriteBuffer[1] = 0
# WriteBuffer[2] = 0
# WriteBuffer[3] = 0
# WriteBuffer[4] = 0
# WriteBuffer[5] = 0
# WriteBuffer[6] = 0
# WriteBuffer[7] = 0
# WriteBuffer[0] = 0x90
# ReadBuffer[0] = 0
# for i in range(0, 8):
#     WriteBuffer[1 + i] = i

# print('len:',len(WriteBuffer))
while True:
    ret = i2c.IIC_WriteReadBytes(dev, 0, 0x48, i2c.byref(WriteBuffer), 1, i2c.byref(ReadBuffer), len(ReadBuffer), 100)
    # ret = i2c.IIC_WriteReadBytes(dev, 0, 0x48, i2c.byref(WriteBuffer), 1, i2c.byref(ReadBuffer), 1, 100)
    if ret != i2c.IIC_SUCCESS:
        print("WriteRead iic faild!")
        exit()
    else:
        print("WriteRead iic sunccess!")
        # print(f"Read Data:{sum(ReadBuffer)/len(ReadBuffer)}")
        print(f"Read Data:")
        for i in range(0, len(ReadBuffer)):
            # print("%02X " % ReadBuffer[i], end='')
            print(ReadBuffer[i], end=' ')
        print("")
    sleep(1)
# Close device
ret = i2c.USB_CloseDevice(dev)
if (bool(ret)):
    print("Close device success!")
else:
    print("Close device faild!")
    exit()
